define(["../common"], function() {
	require(["bootstrap", "bootstrapswitch"], function() {
		var sel = {
			// 选项卡相关	
			tabs: "#saletabs",							// 销售单选项卡列表.HTML
			tab: function(id) {return "[id^='sale_" + (id !== undefined ? id : "") + "']";},						// 销售单选项卡(项).HTML
			
			// 商品录入相关
			saleTypes: function(id) {return "[id^='saleTypes_" + (id !== undefined ? id : "") + "']";},				// 商品出售类型下拉列表(行).HTML
			saleTypeLabel: "#saleTypeLabel",			// 当前商品出售类型.文本
			putupBt: "#putupBt",						// 挂起销售单.按钮
			delBt: "#delBt",							// 删除销售单.按钮
			code: "#code",								// 商品编码.表单项
			manualBt: function(id) {return "[id^='manualBt_" + (id !== undefined ? id : "") + "']";},				// 商品添加.按钮
			totalMoney: "#totalMoney",					// 合计金额.文本
			
			// 商品筛选相关
			filterList: "#filterList",					// 筛选列表.HTML
			filterItems: function(id) {return "[id^='filterItems_" + (id !== undefined ? id : "") + "']";},			// 筛选列表(行).HTML
			
			// 购买商品列表相关
			saleId: "#saleId",							// 出售单ID.表单项
			listTitle: "#listTitle",					// 商品列表头.HTML
			listBody: "#goodslist tbody",				// 商品列表.HTML
			listGoods: function(id) {return "[id^='goods_" + (id !== undefined ? id : "") + "']";},					// 商品列表(行).HTML
			saleGoodsId: function(id) {return "[id^='saleGoodsId_" + (id !== undefined ? id : "") + "']";},			// 出售单商品ID.表单项
			storeGoodsId: function(id) {return "[id^='storeGoodsId_" + (id !== undefined ? id : "") + "']";},		// 商品ID.表单项
			saleType: function(id) {return "[id^='saleType_" + (id !== undefined ? id : "") + "']";},				// 商品出售类型.表单项
			tnum: "[id^='tnum_']",						// 商品序号.文本
			tprice: function(id) {return "[id^='tprice_" + (id !== undefined ? id : "") + "']";},					// 商品单价.文本
			amount: function(id) {return "[id^='amount_" + (id !== undefined ? id : "") + "']";},					// 商品购买量.表单项
			cost: function(id) {return "[id^='cost_" + (id !== undefined ? id : "") + "']";},						// 商品小计.表单项
			tcost: function(id) {return "[id^='tcost_" + (id !== undefined ? id : "") + "']";},						// 商品小计.文本
			tcode: function(id) {return "[id^='tcode_" + (id !== undefined ? id : "") + "']";},						// 商品编码.文本
			delGoodsBt: function(id) {return "[id^='delGoods_" + (id !== undefined ? id : "") + "']";},				// 删除商品.按钮
			
			// 填写金额相关
			subtotal: "#subtotal",						// 手输金额.表单项
			subtotalBt: function(id) {return "[id^='subtotalBt_" + (id !== undefined ? id : "") + "']";},			// 完成填写金额.按钮
			
			// 结算相关
			total4Cashback: "#total4Cashback",			// 合计金额.文本
			total4Discount: "#total4Discount",
			pay4Cashback: "#pay4Cashback",				// 应付.文本
			pay4Discount: "#pay4Discount",
			pay4Settle: "#pay4Settle",
			cashback: "#cashback",						// 返现金额.表单项
			discount: "#discount",						// 折扣率.表单项
			pay: "#pay",								// 现收.表单项
			change4Settle: "#change4Settle",			// 找零.文本
			change4Settle0: "#change4Settle_input",			// 找零.表单项
			cashbackBt: function(id) {return "[id^='cashbackBt_" + (id !== undefined ? id : "") + "']";},	
			discountBt: function(id) {return "[id^='discountBt_" + (id !== undefined ? id : "") + "']";},	
			settleBt: function(id) {return "[id^='settleBt_" + (id !== undefined ? id : "") + "']";},				// 提交结算.按钮
			
			// 找零相关
			change : "#change",		// 找零.文本
			
			// 表单
			form: function(id) {return "[id^='form_" + (id !== undefined ? id : "") + "']";},
			
			// 对话框
			modal: function(id) {return "[id^='modal_" + (id !== undefined ? id : "") + "']";},	
			modalBt: function(id) {return "[id^='modalBt_" + (id !== undefined ? id : "") + "']";},	
			
			// 打印相关
			printFrame: "#printframe",
				
			clientSwitch: "#clientSwitch"				// 客户屏开关
				
		};
		// 设置参数
		var setting = null;
		// 订单序列号（递增）
		var putupSerial = 0;
		// 商品序列号（递增）
		var goodsSerial = 0;
		// 当前销售单ID
		var curSaleId = null;
		var curSerialCode = null;
		// 商品筛选列表对应的数据
		var filterDatas = [];
		// 焦点类型,用于辅助键盘事件处理
		var focusTypes = {
			ADD: "add",				// 查找商品
			FILTER: "filter",		// 筛选商品
			SUBTOTAL: "subtotal", 	// 填写商品金额
			AMOUNT: "amount",		// 修改商品购买量
			SETTLE: "settle",		// 结算
			CASHBACK: "cashback",	// 返现
			DISCOUNT: "discount"	// 折扣
		};
		// 当前焦点
		var focusType = focusTypes.ADD;
		// 商品出售类型
		var saleTypes = {
			SALE: 0,				// 出售
			FREE: 1					// 赠送
		}
		// 当前商品出售类型
		var saleType = saleTypes.SALE;
		// 对话框类型
		var modalTypes = {
			SUBTOTAL: "subtotal",	// 商品小计
			LOGIN: "login",			// 营业员登录
			SETTLE: "settle",		// 结算
			DISCOUNT: "discount",	// 折扣
			CASHBACK: "cashback",	// 返现
			CHANGE: "change",		// 找零
			TIP: "tip"				// 提示
		}
		// 表单类型
		var formTypes = {
			CODE: "code",				// 查询编码
			GOODS_LIST: "goods_list",	// 商品列表
			SUBTOTAL: "subtotal",		// 商品小计
			LOGIN: "login",				// 营业员登录
			SETTLE: "settle",			// 结算
			DISCOUNT: "discount",		// 折扣
			CASHBACK: "cashback",		// 返现
			CHANGE: "change"			// 找零
		};
		// 结算类型
		var settleTypes = {
			DEFAULT: "default",			// 默认
			DISCOUNT: "discount",		// 折扣
			CASHBACK: "cashback",		// 返现		
		};
		var settleType = settleTypes.DEFAULT;
		// 商品筛选列表模板内容
		var filterTemp = $(sel.filterList).html();	
		// 商品记录模板内容
		var itemTemp = $(sel.listBody).html();
		var printFrameWin = $(sel.printFrame).get(0).contentWindow;// frame window
		
		$(sel.filterList).empty();
		$(sel.listBody).empty().show();
		
		loadjs(["validator"], initValidate);
		initEvent();
		initSaleList();
		
		/**
		 * 初始化表单验证
		 */
		function initValidate() {
			
			$.validator.config({
				stopOnError: true,
				msgMaker: false,
				invalid: function(form, errors) {
					showMsg(errors[0], "error");
				},
				messages: {
					required: '{0}不能为空',
					money: "{0}金额无效"
				}
			});
			
			$(sel.form(formTypes.CASHBACK)).validator({
				rules: {
					cashback: function(el) {
						if (parseFloat($(el).val()) > parseFloat($(sel.total4Cashback).html())) {
							return "{0}金额不能大于合计金额";
						}
					}
				},
				fields: {
					cashback: "返现:required;money;cashback"
				}
			});
			
			$(sel.form(formTypes.CHANGE)).validator({
				//...
			});
			
			$(sel.form(formTypes.CODE)).validator({
				fields: {
					code: "商品条码:required;digits; match[gt, 0]"
				}
			});
			
			$(sel.form(formTypes.DISCOUNT)).validator({
				fields: {
					discount: "折扣:required; integer[+0]; range[0~100]"
				}
			});
			
			$(sel.form(formTypes.GOODS_LIST)).validator({
				//...
			});
			
			$(sel.form(formTypes.LOGIN)).validator({
				//...
			});
			
			$(sel.form(formTypes.SETTLE)).validator({
				rules: {
					pay: function(el) {
						if (parseFloat($(el).val()) < parseFloat($(sel.pay4Settle).html())) {
							return "{0}金额不足";
						}
					}
				},
				fields: {
					pay: "现收:required;money;pay"
				}
			});
			
			$(sel.form(formTypes.SUBTOTAL)).validator({
				fields: {
					subtotal: "金额:required;money"
				}
			});
			
			// 商品列表表单验证
			initGoodsesValid();
			
		}

		/**
		 * 初始化操作事件
		 */
		function initEvent() {
			$(sel.form(formTypes.CASHBACK)).on('valid.form', function(e, form){
				//...
				settleType = settleTypes.CASHBACK;
				$(sel.modal(modalTypes.CASHBACK)).modal('hide');
			});
			$(sel.form(formTypes.CHANGE)).on('valid.form', function(e, form){
				//...			
			});
			$(sel.form(formTypes.CODE)).on('valid.form', function(e, form){
				addGoods();
			});
			$(sel.form(formTypes.DISCOUNT)).on('valid.form', function(e, form){
				//...
				settleType = settleTypes.DISCOUNT;
				$(sel.modal(modalTypes.DISCOUNT)).modal('hide');
			});
			$(sel.form(formTypes.GOODS_LIST)).on('valid.form', function(e, form){
				//...
			});
			$(sel.form(formTypes.LOGIN)).on('valid.form', function(e, form){
				//...
			});
			$(sel.form(formTypes.SETTLE)).on('valid.form', function(e, form){
				settleDo();
			});
			$(sel.form(formTypes.SUBTOTAL)).on('valid.form', function(e, form){
				//...
			});
			
			// 切换商品出售类型
			$(sel.saleTypes()).click(function() {
				saleType = parseInt($(this).attr("id").split(/_/)[1]);
				// 显示切换结果,并(特殊处理)保持快捷键能正常显示
				$(sel.saleTypeLabel).html($(this).html()).attr("data-key", "F3").removeAttr("data-key-true");
				
			});
			// 手工添加商品
			$(sel.manualBt()).click(function() {
				// 关闭可能正在显示的其它内容
				$(sel.modal(modalTypes.CHANGE)).modal('hide');
				
				$(sel.form(formTypes.CODE)).trigger('validate');
				return false;
			});
			// 选择商品(编码查询有多个结果时)
			$(document).on('click', sel.filterItems(), function() {
	    		var i = $(this).attr("id").split(/_/)[1];
	    		selectFilterGoods(filterDatas[i]);
	    		return false;
	    	});
			// 填写金额
			$(sel.subtotalBt()).click(function() {
				$(sel.form(formTypes.SUBTOTAL)).trigger('validate');
				return false;
			});
			// 重置结算类型
			$(sel.modalBt(modalTypes.CASHBACK)+","+sel.modalBt(modalTypes.DISCOUNT)).click(function () {
				settleType = settleTypes.DEFAULT;
			});
			// 结算计算
			$(sel.modalBt()).click(function() {
				
				// 关闭可能正在显示的其它内容
				$(sel.filterList).hide();
				$(sel.modal()).modal('hide');
				
				var type = $(this).attr("id").split("_")[1];
				
				// 列表表单验证通过后再触发完成提交
				initGoodsesValid(function() {
					$(sel.modal(type)).modal('show');				
				});
				$(sel.form(formTypes.GOODS_LIST)).trigger('validate');
				return false;
			});
			// 返现计算
			$(sel.cashback).keyup(function() {
				var pay4Cashback = parseFloat($(sel.total4Cashback).html()) - parseFloat($(this).val());
				if (isNaN(pay4Cashback) || pay4Cashback < 0) {
					pay4Cashback = 0;
				}
				$(sel.pay4Cashback).html(pay4Cashback.toFixed(2));
				return false;
			});
			// 完成返现
			$(sel.cashbackBt()).click(function() {
				$(sel.form(formTypes.CASHBACK)).trigger('validate');
				return false;
			});
			// 折扣计算
			$(sel.discount).keyup(function() {
				var pay4Discount = parseFloat($(sel.total4Discount).html()) * (parseFloat($(this).val())/100);
				if (isNaN(pay4Discount) || pay4Discount < 0) {
					pay4Discount = 0;
				}
				$(sel.pay4Discount).html(pay4Discount.toFixed(2));
				return false;
			});
			// 完成折扣
			$(sel.discountBt()).click(function() {
				$(sel.form(formTypes.DISCOUNT)).trigger('validate');
				return false;
			});
			// 完成结算
			$(sel.settleBt()).click(function() {
				// 列表表单验证通过后再触发完成提交
				initGoodsesValid(function() {
					$(sel.form(formTypes.SETTLE)).trigger('validate');
				});
				$(sel.form(formTypes.GOODS_LIST)).trigger('validate');
				return false;
			});
			// 找零计算
			$(sel.pay).keyup(function() {
				var change = parseFloat($(this).val()) - parseFloat($(sel.pay4Settle).html());
				if (isNaN(change) || change < 0) {
					change = 0;
				}
				$(sel.change4Settle).html(change.toFixed(2));
				$(sel.change4Settle0).val(change.toFixed(2));
				return false;
			});
			// 挂起
			$(sel.putupBt).click(function() {
				initGoodsesValid();
				$(sel.form(formTypes.GOODS_LIST)).trigger('validate');
				return false;
			});
			// 取消
			$(sel.delBt).click(function() {
				delDo();
				return false;
			});
			
			// 修改购买数量
			$(document).on('keyup',sel.amount(), function() {
				var vars = $(this).attr("id").split(/_/);
				var id = vars[1] + "_" + vars[2];
				
				if (parseInt($(sel.saleType(id)).val()) === saleTypes.SALE ) {
					var cost = parseFloat($(this).val()) * parseFloat($(sel.tprice(id)).html());
					$(sel.cost(id)).val(cost.toFixed(2));
					$(sel.tcost(id)).html(cost.toFixed(2));
					stat();
				}
				
				return false;
			});
			// 数量验证失败
			$(document).on('invalid.field', sel.amount(), function(e, result, me){
				var vars = $(this).attr("id").split(/_/);
				var id = vars[1] + "_" + vars[2];
				flickerRow(id);
				return false;
			});
			// 删除商品
			$(document).on('click',sel.delGoodsBt(), function() {
				var vars = $(this).attr("id").split(/_/);
				var id = vars[1] + "_" + vars[2];
				$(sel.listGoods(id)).fadeOut(function(){
					
					$(sel.listGoods(id)).remove();
					stat();
					resetNums();
					
					// 返回编辑录入状态
					focusType = focusTypes.ADD;
					$(document).click();
					
				});
				
				return false;
			});
			
			// 进入填写金额之前,变更内容,同时避免用户看到窗体内容变动(用户体验问题)
			$(sel.modal(modalTypes.SUBTOTAL)).on('show.bs.modal', function (e) {
				$(sel.subtotal).val("");
				//return false;
			});
			// 进入填写金额之后
			$(sel.modal(modalTypes.SUBTOTAL)).on('shown.bs.modal', function (e) {
				focusType = focusTypes.SUBTOTAL;
				$(sel.subtotal).focus();
				return false;
			});
			// 退出填写金额之后
			$(sel.modal(modalTypes.SUBTOTAL)).on('hidden.bs.modal', function (e) {
				focusType = focusTypes.ADD;
				$(document).click();
				return false;
			});
			
			// 进入返现之前,变更内容,同时避免用户看到窗体内容变动(用户体验问题)
			$(sel.modal(modalTypes.CASHBACK)).on('show.bs.modal', function (e) {
				$(sel.total4Cashback).html($(sel.totalMoney).html());
				$(sel.pay4Cashback).html("0.00");
				$(sel.cashback).val("");
				//return false;
			});
			// 进入返现之后
			$(sel.modal(modalTypes.CASHBACK)).on('shown.bs.modal', function (e) {
				focusType = focusTypes.CASHBACK;
				$(sel.cashback).focus();
				return false;
			});
			// 退出返现之后
			$(sel.modal(modalTypes.CASHBACK)).on('hidden.bs.modal', function (e) {
				$(sel.modalBt(modalTypes.SETTLE)).click();
				return false;
			});
			
			// 进入折扣之前,变更内容,同时避免用户看到窗体内容变动(用户体验问题)
			$(sel.modal(modalTypes.DISCOUNT)).on('show.bs.modal', function (e) {
				$(sel.total4Discount).html($(sel.totalMoney).html());
				$(sel.pay4Discount).html("0.00");
				$(sel.discount).val("");
				//return false;
			});
			// 进入折扣之后
			$(sel.modal(modalTypes.DISCOUNT)).on('shown.bs.modal', function (e) {
				focusType = focusTypes.DISCOUNT;
				$(sel.discount).focus();
				return false;
			});
			// 退出折扣之后
			$(sel.modal(modalTypes.DISCOUNT)).on('hidden.bs.modal', function (e) {
				$(sel.modalBt(modalTypes.SETTLE)).click();
				return false;
			});
			
			// 进入结算之前,变更内容,同时避免用户看到窗体内容变动(用户体验问题)
			$(sel.modal(modalTypes.SETTLE)).on('show.bs.modal', function (e) {
				var pay4Settle = $(sel.totalMoney).html();
				if (settleType == settleTypes.CASHBACK) {
					pay4Settle = $(sel.pay4Cashback).html();					
				} else if (settleType == settleTypes.DISCOUNT) {
					pay4Settle = $(sel.pay4Discount).html();					
				}
				$(sel.pay4Settle).html(pay4Settle);	
				$(sel.change4Settle).html("0.00");
				$(sel.pay).val("");
				//return false;
			});
			// 进入结算之后
			$(sel.modal(modalTypes.SETTLE)).on('shown.bs.modal', function (e) {
				focusType = focusTypes.SETTLE;
				$(sel.pay).focus();
				return false;
			});
			// 退出结算之后
			$(sel.modal(modalTypes.SETTLE)).on('hidden.bs.modal', function (e) {
				//$(sel.pay4Settle).empty();
				//$(sel.change4Settle).empty();
				//$(sel.pay).val("");
				
				focusType = focusTypes.ADD;
				$(document).click();
				
				return false;
			});
			
			// 进入找零提示之前,变更内容,同时避免用户看到窗体内容变动(用户体验问题)
			$(sel.modal(modalTypes.CHANGE)).on('show.bs.modal', function (e) {
				$(sel.change).html($(sel.change4Settle).html());				
				$(document).trigger('client.showChange');// 使客户屏显示找零提示
				//return false;
			});
			// 退出找零提示之前
			$(sel.modal(modalTypes.CHANGE)).on('hide.bs.modal', function (e) {				
				$(document).trigger('client.hideChange');// 使客户屏关闭找零提示
				//return false;
			});
			
			// 退出信息提示之后
			$(sel.modal(modalTypes.TIP)).on('hidden.bs.modal', function (e) {
				$(document).click();
				return false;
			});
			
			$(document).click(function(event) {
				
				// 进行其它非录入操作时，使指定文本框获得焦点
				if (!$(event.target).is("input")) {
					
					if (focusType === focusTypes.ADD) {
						$(sel.code).focus().select();
						
					} else if (focusType === focusTypes.FILTER) {
						focusType = focusTypes.ADD
						$(sel.filterList).hide();
						$(sel.code).focus().select();
						
					} else if (focusType === focusTypes.SUBTOTAL) {
						$(sel.subtotal).focus().select();
						
					} else if (focusType === focusTypes.AMOUNT) {
						var curIndex = $(sel.listGoods()).filter(".active").index(sel.listGoods());
						$(sel.amount()).eq(curIndex).focus().select();
						
					} else if (focusType === focusTypes.SETTLE) {
						$(sel.pay).focus().select();
						
					}
				}
				
			});
			$(document).dblclick(function() {
				return false;
			});
			
			// 调整性处理:解决弹出框显示时,页面发生微小变形(用户体验问题)
			$('.modal').on('shown.bs.modal', function (e) {
				$("body").css("padding-right", "0px");
				$("body").css("overflow", "auto");
			});
			
			// 保持表头与商品列表在布局上的"连接"关系(即页面变形问题)
			$(window).resize(function() {
				$("#listPanel").css("padding-top", $("#headPanel").outerHeight() - 1);
			});

		}
		
		
		/**
		 * 获取销售单(ID)列表
		 */ 
		function initSaleList() {
			showMsg("请稍候...", 'load');
			$.get(g_shopDomain + "/localSale/v1.1/initData/json", function(data) {
				showMsg().modal('hide');
				if (data.status !== 0) {
					showMsg(data.message, 'error');
					return;
				}
				setting = $.parseJSON(data.result.localSetting);
				
				// 打开客户屏
				if (setting.clientScreen.isOpenClientScreen) {
					$(sel.clientSwitch).click();
				}
				
				// 传递打印参数
				printFrameWin.setSetting(setting);		
				
				var list = data.result.localSales;
				var sale = null;
				for (var i in list) {
					putupSerial++;
					sale = list[i];
					$(sel.tabs).append('<li id="sale_' + sale.saleId + '"><a href="#">订单' + putupSerial + '</a></li>');
				}
				initEvent_();
				if (sale) {
					activeSale(sale.saleId);
				} else {
					addNewSale();
				}
			});
			
			function initEvent_() {
				$(document).on('click', sel.tab(), function() {
					if (doing()) return; 
					var saleId = ($(this).attr("id").split(/_/))[1];
					activeSale(saleId);
					return false;
				});
			}
		}

		/**
		 * 选中(激活)销售单选项卡
		 */
		function activeSaleTab(saleId) {
			if (!saleId && $(sel.tab()).length === 0) {
				addNewSale();
				return null;
			} 
			
			var $oldTab = $(sel.tab() + ".active").removeClass("active");
			
			var text = null;
			var $saleTab = null;
			
			if (!saleId) {
				if ($(sel.tab()).length === 0) {
					putupSerial++;
					$(sel.tabs).append("<li id='sale_" + saleId + "'><a>订单" + putupSerial +"</a></li>");
					$saleTab = $(sel.tab(saleId));
				} else {
					$saleTab = $(sel.tab()).eq($(sel.tab()).length - 1);
					saleId = $saleTab.attr("id").split(/_/)[1];
				}
				
			} else {
				$saleTab = $(sel.tab(saleId));
				if ($saleTab.length === 0) {
					putupSerial++;
					$(sel.tabs).append("<li id='sale_" + saleId + "'><a>订单" + putupSerial +"</a></li>");
					$saleTab = $(sel.tab(saleId));
				}
			}
			$saleTab.addClass("active");
			$(document).trigger('showKey');
			return saleId;
		}
		
		/**
		 * 进入销售单商品出售
		 */
		function activeSale(saleId) {
			saleId = activeSaleTab(saleId);
			if (saleId) {
				initSale(saleId);
			}
			
		}
		
		/**
		 * 新建销售单
		 */
		function addNewSale(params, callback) {
			
			showMsg("请稍候...", 'load');
			$.post(g_shopDomain + "/localSale/v1.1/addDo/json", params, function(data) {
				showMsg().modal('hide');
				if (callback) {
					if (!callback(data)) {
						return;
					}
				}
				if (data.status !== 0) {
					showMsg(data.message, 'error');
					return;
				}
				//var saleId = data.result;
				activeSale(data.result);
			});
		}

		/**
		 * 初始化销售单显示
		 */
		function initSale(saleId) {
			curSaleId = saleId;
			$(sel.saleId).val(curSaleId);
			$(sel.listBody).empty();
			stat();
			loadData();
		}
		
		// 初始化商品列表表单验证
		function initGoodsesValid(callback) {
			var fieldsStr = "{";
			$(sel.amount()).each(function(i, el) {
				fieldsStr += (i > 0 ?"," : "") + "'#" + $(this).attr("id") + "':'数量:required;money'";
			});
			fieldsStr += "}";
			var fields = null;
			eval("fields=" + fieldsStr);
			$(sel.form(formTypes.GOODS_LIST)).validator({
				fields: fields,
				valid: function(form) {
					if ($(sel.form(formTypes.GOODS_LIST)).find(sel.listGoods()).length === 0) {
						showMsg("请先添加商品", 'error');
						return;
					}
					renameForm();
					callback?callback(form):putUpDo(form);
				}
			});
		}
		
		// 加载销售单数据
		function loadData() {
			if (doing()) return; 
			showMsg("请稍候...", 'load');
			doing(true);
			$.post(g_shopDomain + "/localSale/v1.1/one/json", {saleId: curSaleId}, function(data) {
				showMsg().modal('hide');
				doing(false);
				if (data.status !== 0) {
					showMsg(data.message, 'error');
					return;
				}			
				// localSale
				var sale = data.result;
				curSerialCode = sale.serialCode;
				
				// 为购物小票中的二维码打印做准备
				printFrameWin.initPrintQrcode(curSerialCode);
				
				var list = sale.localSaleGoodses;
				var lsg;// localSaleGoods
				var sg;// storeGoods
				for (var i in list) {
					lsg = list[i];
					sg = lsg.storeGoods;
					sg.saleGoodsId = lsg.saleGoodsId;
					sg.saleType = lsg.type;
					sg.amount = lsg.amount;
					sg.cost = lsg.cost;
					appendGoods(sg);
				}
				$(document).click();
				
				$(document).trigger('client.showShoppingQrcode');
			});
		}
		
		function selectFilterGoods(sg) {
			$(sel.filterList).hide();
			
			// 打秤类:
			if (parseInt(sg.barCode) < 100000) {
				showSubtotalForm(sg);
	    		return;
			}
			
			appendGoods(sg);
		}
		
		// 显示金额填写表单
		function showSubtotalForm(sg) {
			
			$(sel.modal(modalTypes.SUBTOTAL)).modal('show');
			
			initSubtotalValid(function(form) {
				
				$(sel.modal(modalTypes.SUBTOTAL)).modal('hide');
				sg.cost = parseFloat($(sel.subtotal).val());
				sg.amount = parseFloat(sg.cost/sg.price);
				
				// 赠送品,只利用金额计算数量
				if (saleType === saleTypes.FREE) {
					sg.cost = 0;
				}
				
				appendGoods(sg);
				
			});
		}
		
		// 初始化商品金额表单验证
		function initSubtotalValid(callback) {
			$(sel.form(formTypes.SUBTOTAL)).validator({
				fields: {
					subtotal: "金额:required;money"
				},
				valid: function(form) {
					callback?callback(form):void(0);
				}
			});
		}
		
		function addGoods() {
			if (doing()) return; 
			showMsg("请稍候...", 'load');
			doing(true);
			
			$(sel.filterList).hide().empty();
			
			var barCode = $(sel.code).val();
			$(sel.code).val("");
			$.post(g_shopDomain + "/storeGoods/code/json", {barCode: barCode, orderField: "barCode"}, function(data) {
				showMsg().modal('hide');
				doing(false);
				$(document).click();// 使焦点回到编码输入框
				if (data.status !== 0) {
					showMsg(data.message, 'error');
					
					return;
				} 
				// storeGoods list
				var list = data.result.list;
				if (!list || list.length === 0) {
					showMsg("查无商品", 'error');
					return;
				}
				
				var sg = null;
				if (list.length === 1) {
					
					sg = list[0];
					if (parseInt(sg.barCode) > 99999) {
						appendGoods(sg);
						return;
					} 
					
					var code = parseInt(barCode);
					// 打秤类
					if (code > 2e12 && code < 29e11) {// 从编码中获取金额
						var cost = code%1e6;
						cost = parseInt(cost/10)/100;
						sg.cost = cost;
						sg.amount = parseFloat((cost/sg.price));
						appendGoods(sg);
						
					} // 填写金额
					else {
						showSubtotalForm(sg);
					}
					
				} else {
					
					filterDatas = list;
					$(sel.filterList).show();
					var html;
					for (var i in list) {
						sg = list[i];
						html = filterTemp
						.replace(/\-\{index\}\-/g, i)
						.replace(/\-\{barCode\}\-/g, sg.barCode)
						.replace(/\-\{name\}\-/g, sg.name)
						.replace(/\-\{price\}\-/g, sg.price + "/" + sg.unit);
						$(sel.filterList).append(html);
					}
					
				}
				
			});
					
		}
		
		function appendGoods(sg) {
			// 注意:sg在storeGoods对象的基础上有扩展有部分localSaleGoods属性
			
			// 出售方式
			if (sg.saleType === undefined) {
				sg.saleType = saleType;
			}

			// 购买量及费用
			if (sg.cost === undefined || sg.amount === undefined) {
				if (sg.saleType === saleTypes.FREE) {
					sg.cost = 0;
				} else {
					sg.cost = sg.price;
				}
				sg.amount = 1;
			}
			
			var id = sg.storeGoodsId;
			
			// format: saleType_[storeGoodsId]_[goodsSerial]
			var $saleType = $(sel.saleType(id) + "[value='" + sg.saleType + "']");
			
			// 列表中已经存在此商品
			if ($saleType.length > 0) {
				
				var serial = $saleType.attr("id").split(/_/)[2];
				id += "_" + serial;
				
				var preCost = parseFloat($(sel.cost(id)).val());
				var preAmount = parseFloat($(sel.amount(id)).val());
				var cost = sg.cost + preCost;
				var amount = sg.amount + preAmount;
				$(sel.amount(id)).val(amount.toFixed(2));
				$(sel.cost(id)).val(cost.toFixed(2));
				$(sel.tcost(id)).html(cost.toFixed(2));
				
			} else {
				
				goodsSerial++;
				id += "_" + goodsSerial;
				
				var itemHtml = itemTemp
				.replace(/\-\{id\}\-/g, id)
				.replace(/\-\{num\}\-/g, $(sel.listGoods()).length + 1)
				.replace(/\-\{saleGoodsId\}\-/g, sg.saleGoodsId === undefined ? "" : sg.saleGoodsId)
				.replace(/\-\{storeGoodsId\}\-/g, sg.storeGoodsId)
				.replace(/\-\{code\}\-/g, sg.barCode)
				.replace(/\-\{type\}\-/g, sg.saleType)
				.replace(/\-\{typeLabel\}\-/g, getSaleTypeLabe(sg.saleType))
				.replace(/\-\{name\}\-/g, sg.name)
				.replace(/\-\{price\}\-/g, sg.price)
				.replace(/\-\{amount\}\-/g, sg.amount.toFixed(2))
				.replace(/\-\{unit\}\-/g, sg.unit)
				.replace(/\-\{cost\}\-/g, sg.cost.toFixed(2));
				$(sel.listBody).prepend(itemHtml);
				
			}
			
			stat();
			
			focusType = focusTypes.ADD;
			$(document).click();
			
		}
		
		function getSaleTypeLabe(saleType) {
			return saleType === saleTypes.FREE ? '<span class="label label-warning label-free">赠</span>' : "";
		}
		
		/**
		 * 商品列表表单重命名
		 */
		function renameForm() {
			var $form = $(sel.form(formTypes.GOODS_LIST));
			
			$form.find(sel.listGoods()).each(function(i, el) {
				var $tr = $(this);
				
				// goods_[storeGoodsId]_[goodsSerial]
				var vars = $tr.attr("id").split(/_/);
				var id = vars[1] + "_" + vars[2];
				
				$tr.find(sel.storeGoodsId(id)).attr("name", "fsg[" + i + "].storeGoods.storeGoodsId");
				$tr.find(sel.saleGoodsId(id)).attr("name", "fsg[" + i + "].saleGoodsId");
				$tr.find(sel.saleType(id)).attr("name", "fsg[" + i + "].type");
				$tr.find(sel.amount(id)).attr("name", "fsg[" + i + "].amount");
				$tr.find(sel.cost(id)).attr("name", "fsg[" + i + "].cost");
				
			});
			return $form;
		}
		
		/**
		 * 提交结算
		 */
		function settleDo() {
			if (doing()) return; 
			showMsg("请稍候...", 'load');
			var params = $(sel.form(formTypes.GOODS_LIST)).serialize() + "&" + $(sel.form(formTypes.SETTLE)).serialize();
			$.post(g_shopDomain + "/order/addDo/json", params, function(data) {
				// storeGoodsId or orderCode
				var result = data.result;
				if (data.status !== 0) {
					showMsg(data.message, 'error');
					// 闪动行
					//flickerRow(result);
					return;
				}
				
				$(sel.modal(modalTypes.SETTLE)).modal('hide');
				$(sel.modal(modalTypes.CHANGE)).modal('show');				
				
				// 准备商品的打印内容
				printFrameWin.initPrintGoods();
				
				// 打印
				if (setting.print.isPrintReceipt) {
					printFrameWin.focus();// (ie兼容)不加则始终打印顶层页面
					printFrameWin.print();
				}				
				
				// 删除导航标题
				$(sel.tab(curSaleId)).remove();
				// 进行下一个销售
				activeSale();
			});
		}
		
		function putUpDo() {
			if (doing()) return; 
			showMsg("请稍候...", 'load');
		
			$.post(g_shopDomain + "/localSale/v1.1/updateDo/json", $(sel.form(formTypes.GOODS_LIST)).serialize(), function(data) {
				if (data.status !== 0) {
					showMsg(data.message, 'error');
					return;
				}
				showMsg("挂起成功!");
				addNewSale();
			});
		}
		
		function delDo() {
			if (doing()) return; 
			showMsg("请稍候...", 'load');
			
			$.post(g_shopDomain + "/localSale/v1.1/delDo/json", {saleId: curSaleId}, function(data) {
				if (data.status !== 0) {
					showMsg(data.message, 'error');
					return;
				}
				showMsg("删除成功!");
				
				// 删除导航标题
				$(sel.tab(curSaleId)).remove();
				activeSale();
			});
		}
		
		// 给单中每个商品赋个序号,从大到小
		function resetNums() {
			var $nums = $(sel.tnum);
			var len = $nums.length;
			$nums.each(function(i, el) {
				$(this).html(len - i);
			});
		}
		
		// 统计金额
	    function stat() {
	    	var money = 0;
	    	$(sel.cost()).each(function() {
	    		money +=parseFloat($(this).val());
	    	});
	    	$(sel.totalMoney).html(money.toFixed(1) + "0"); // 金额四舍五入保留一位小数
	    	
	    	// 触发客户屏显示
	    	$(document).trigger('client.changeGoodsList');
	    }
	    
	    // 清理页面内容
	    function clearShowing() {
	    	$(sel.filterList).hide();
			$(sel.modal()).modal('hide');
	    }
	    
	    // 行闪动
	    function flickerRow(id) {
	    	$(sel.listGoods(id)).fadeTo('fast',0.1,function() {$(this).fadeTo('fast',1);}); 
	    }
		
		// 消息提示
		function showMsg(msg, type) {
			var KEY_INDEX = "showMsgIndex";			
			var $el = $(sel.modal(modalTypes.TIP));
			
			clearTimeout(parseInt($el.data(KEY_INDEX)));
			
			if (!msg)return $el;
			
			$loading = $el.find(".loading").hide();
		    $el.find(".form-control-static").html(msg);
		    $el.finish().modal('show');
		    if (type !== "load") {
				var index = setTimeout(function() {
		        	showMsg().modal('hide');
		        },1500);
		        $el.data(KEY_INDEX, index);
		    } else {
		    	$loading.show();
		    }
		    return $el;
		}
		
		/**
		 * 客户屏相关
		 */
		(function($) {
			
			var cWin = null; // client window
			
			$.fn.bootstrapSwitch.defaults.size = 'small';
			$.fn.bootstrapSwitch.defaults.onColor = 'success';
			$.fn.bootstrapSwitch.defaults.onText = '开';
			$.fn.bootstrapSwitch.defaults.offText = '关';
			$.fn.bootstrapSwitch.defaults.handleWidth = 30;
			$.fn.bootstrapSwitch.defaults.labelWidth = 0;
			
			$(sel.clientSwitch).bootstrapSwitch({
				onSwitchChange: function(event, state) {
					state ? openClientScreen() : closeClientScreen();
				}
			});
			
			// 触发客户屏显示记账二维码
			$(document).on('client.showShoppingQrcode', function() {
				if (cWin && cWin.clientShowShoppingQrcode) cWin.clientShowShoppingQrcode(curSerialCode);
			});
			// 触发客户屏更新购物列表
			$(document).on('client.changeGoodsList', function() {
				if (cWin && cWin.clientChangeGoodsList) cWin.clientChangeGoodsList();
			});
			// 触发客户屏显示找零
			$(document).on('client.showChange', function() {
				if (cWin && cWin.clientShowChange) cWin.clientShowChange();
			});
			// 触发客户屏关闭找零
			$(document).on('client.hideChange', function() {
				if (cWin && cWin.clientHideChange) cWin.clientHideChange();
			});
			
			/* 供子窗口调用 */
			
			// 获取设置参数
			window.setClientScreenSetting = function() {
				if (cWin && cWin.clientSetSetting) cWin.clientSetSetting(setting);
			}
			// 显示记账二维码
			window.showClientShoppingQrcode = function() {
				if (cWin && cWin.clientShowShoppingQrcode) cWin.clientShowShoppingQrcode(curSerialCode);
			}

			// 打开客户屏
			function openClientScreen() {
				var args = "width=500,height=150";
				var localArgs = Common.getLocalStorage("clientScreenArgs");
				if (localArgs) {
					var availLeft = parseInt(localArgs.split(/,/)[0]),availTop = parseInt(localArgs.split(/,/)[1]);
					if (availLeft !== screen.availLeft || availTop !== screen.availTop) {
						args = "left=" + availLeft + ",top=" + availTop;
					} else {
						//args = testScreen();
					}
				} else {
					//args = testScreen();
				}
				if (args) {
					cWin = window.open(g_shopDomain + "/localSale/v1.1/clientScreen", "clientScreen", args + ",dialog=yes,location=no,alwaysLowered=yes,close=no");
					cWin.onClose = function() {
						$(sel.clientSwitch).attr("checked", false);
					}
					
				}
			}
			
			// 关闭客户屏
			function closeClientScreen() {
				cWin ? cWin.close() : void(0);
			}
			
			/*
			function testScreen() {
				var sw = window.screen.width;
				var sh = window.screen.height;
				var testArgs = "outerHeight=1,outerWidth=1,innerHeight=0,innerWidth=0,screenX=0,screenY=0,status=no,scrollbars=no,locationbar=no,location=no,titlebar=no,toolbar=no,directions=no,resizable=no";
				var testPath = g_resDomain + "/page/screentest.html";
				// testWindow
				var tw = window.open(testPath, "test1", ',left=0,top=-500,' + testArgs);
				if (tw.screen.availTop === window.screen.availTop && tw.screen.availLeft === window.screen.availLeft) {
					tw = window.open(testPath, "test2", ',left='+ sw +',top=500,' + testArgs);
					if (tw.screen.availTop === window.screen.availTop && tw.screen.availLeft === window.screen.availLeft) {
						tw = window.open(testPath, "test3", ',left=0,top='+ sh +',' + testArgs);
						if (tw.screen.availTop === window.screen.availTop && tw.screen.availLeft === window.screen.availLeft) {
							tw = window.open(testPath, "test4", ',left=-500,top=0,' + testArgs);
						}
					}
				}
				
				if (tw.screen.availTop !== window.screen.availTop || tw.screen.availLeft !== window.screen.availLeft) {
					return "left=" + tw.screen.availLeft + ",top=" + tw.screen.availTop;
				}
				return null;
			}
			*/
			
		})($);

		/**
		 * 快捷键相关
		 */ 
		(function($) {
			
			var isShowKey_ = false;		// 键盘符显示状态
			var specialHandles_ = [];	// 特殊键盘操作事件对象(主要是一些动态变化的键盘操作)
			var isInit_ = false;		// 是否注册过键盘操作
			
			require(["jwerty"], initJwerty_);
			
			$(document).on('showKey', function() {
				require(["jwerty"], function() {
					if (!isInit_) {
						initJwerty_();
					} else {
						initJwerty4Special_();
					}
					showKey_(isShowKey_);
				});
			});
			
			// 注册键盘事件
			function initJwerty_() {
				
				isInit_ = true;
				
				initJwerty4Special_();
				
				// 显示快捷键
				jwerty.key('F1', function () { 
					setTimeout(function () {
						$("[id^='shortcut_']").toggle();
						showKey_(isShowKey_?false:true);
					}); 
					return false;
				});
				// 重复打印
				jwerty.key('F2', function () { 
					printFrameWin.focus();
					printFrameWin.print(); 
					return false;
				});
				// 切换出售类型
				jwerty.key('F3/forward-slash/num-slash', function () {
					clearShowing();
					$(sel.saleTypes()).not(sel.saleTypes(saleType)).click(); 
					return false;
				});
				// 进入结算
				jwerty.key('F4', function () {
					clearShowing();
					$(sel.modalBt(modalTypes.SETTLE)).click();
					return false;
				});
				// 挂起订单
				jwerty.key('F10/num-plus', function () {
					clearShowing();
					$(sel.putupBt).click();
					return false;
				});
				// 显示客户屏
				jwerty.key('F12', function () {
					$(sel.clientSwitch).click();
					return false;
				});
				// 取消订单
				jwerty.key('del', function () { 
					clearShowing();
					$(sel.delBt).click();
					return false;
				});
				// 折扣
				jwerty.key('num-star', function () {
					clearShowing();
					$(sel.modalBt(modalTypes.DISCOUNT)).click();
					return false;
				});
				// 返现
				jwerty.key('num-subtract', function () {
					clearShowing();
					$(sel.modalBt(modalTypes.CASHBACK)).click();
					return false;
				});
				// 选择列表中上一个商品
				jwerty.key('↑', function () { 
					arrowKey_('up'); 
					return false;
				});
				// 选择列表中下一个商品
				jwerty.key('↓', function () { 
					arrowKey_(); 
					return false;
				});
				// 删除选中的商品
				jwerty.key('d', function () {
					var curIndex = $(sel.amount()).filter(":focus").index(sel.amount());
					if (curIndex > -1) {
						$(sel.delGoodsBt()).eq(curIndex).trigger('click');
						return false;
					}
				});
				jwerty.key('esc', escKey_);
				jwerty.key('enter', enterKey_);
			}
			
			// 注册动态变化键盘操作
			function initJwerty4Special_() {
				
				// 再次注册键盘事件之前先删除原事件,避免重复
				for (var i in specialHandles_) {
					specialHandles_[i].unbind();
				}
				// 订单1-n
				$(sel.tab()).each(function(i) {
					specialHandles_[i] = jwerty.key('alt+' + (i + 1), (function(i) { 
						return function () { 
							clearShowing(); 
							$(sel.tab()).eq(i).click(); 
							return false;
						};
					})(i));
				});
				
			}
			
			// 显示快捷键
			function showKey_(bool) {
				
				$(sel.tab()).each(function(i, el) {
					var $a = $(el).find("a");
					if (isShowKey_) {
						if ($a.is("[data-key-true]")) {
							$a.html("Ctrl+" + (i+1));
						} else {
							$a.attr("data-key", "Ctrl + " + (i+1));
						}
					} else {
						$a.attr("data-key", "Ctrl+" + (i+1));
					}
				});
				
				if (bool || bool === undefined) {
					isShowKey_ = true;
				} else {
					isShowKey_ = false;
				}
				
				$("[data-key]").each(function() {
					var key = $(this).attr("data-key");
					if (bool || bool === undefined) {
						if (!$(this).is("[data-key-true]")) {
							$(this).attr("data-key", $(this).html());
							$(this).html(key);
							$(this).attr("data-key-true","");
						}					
					} else {
						if ($(this).is("[data-key-true]")) {
							$(this).attr("data-key", $(this).html());
							$(this).html(key);
							$(this).removeAttr("data-key-true");
						}	
					}
				});
				
			}
			
			function escKey_() {
				if (focusType === focusTypes.ADD) {
					$(sel.filterList).hide();
					$(sel.modal(modalTypes.CHANGE)).modal('hide');
				} else if (focusType === focusTypes.FILTER) {
					focusType = focusTypes.ADD;
					$(sel.filterList).hide();
				} else if (focusType === focusTypes.SUBTOTAL) {
					//$(sel.modal(modalTypes.SUBTOTAL)).modal('hide');
				} else if (focusType === focusTypes.AMOUNT) {
					focusType = focusTypes.ADD;
					$(sel.listGoods()).removeClass("active");
				} else if (focusType === focusTypes.SETTLE) {
					//$(sel.modal(modalTypes.SETTLE)).modal('hide');
				} // ...else if
				
				$(document).click();
				return false;
			}
			
			//　回车键处理
			function enterKey_() {
				
				// 筛选商品
				if (focusType === focusTypes.FILTER) {
					
					$(sel.filterItems()).filter(".active").click();
					return false;
					
				} // （编辑回来）添加商品
				else if (focusType === focusTypes.ADD) {
					
					// 不输入编辑按回车，则直接进入结算
					if (!$(sel.code).val()) {
						$(sel.modalBt(modalTypes.SETTLE)).click();
						return false;
					} 
					
					$(sel.manualBt()).eq(0).click();
					return false
					
				} // 填写商品金额
				else if (focusType === focusTypes.SUBTOTAL) {
					
					$(sel.subtotalBt()).eq(0).click();
					return false;
					
				} // 修改商品数量
				else if (focusType === focusTypes.AMOUNT) {
					$(sel.listGoods()).removeClass("active");
					focusType = focusTypes.ADD;
					$(document).click();
					return false;
					
				} // 完成返现
				else if (focusType === focusTypes.CASHBACK) {
					$(sel.cashbackBt()).eq(0).click();
					return false;
					
				} // 完成折扣
				else if (focusType === focusTypes.DISCOUNT) {
					$(sel.discountBt()).eq(0).click();
					return false;
					
				}  // 完成结算
				else if (focusType === focusTypes.SETTLE) {
					$(sel.settleBt()).eq(0).click();
					return false;
					
				} 
				
			}
			
			// 上下箭头键处理
			function arrowKey_(type) {
				
				// 选择查询列表中的商品
				if (focusType === focusTypes.FILTER || (focusType === focusTypes.ADD && $(sel.filterList).is(":visible"))) {
					
					focusType = focusTypes.FILTER;
					$(sel.code).blur();
					
					var $items = $(sel.filterItems());
					if ($items.length === 0) {
						return false;
					}
					var curIndex = $items.filter(".active").index(sel.filterItems());
					var nextIndex = 0;
					$items.removeClass("active");
					if (type === 'up') {
						nextIndex = ((curIndex === -1 || curIndex === 0)  ? $items.length: curIndex) - 1;
					} else {
						nextIndex = (curIndex === $items.length - 1 ? -1 : curIndex) + 1;
					}
					
					var $item = $items.eq(nextIndex); 
					$item.addClass("active");
					
					/*
					// 使显示在可见区域
					var fgt = $(sel.filterList + " table").position();
					var ios = $item.position();// itemOffset
					var $container = $(sel.filterList);
					if (ios.top < 0) {
						$container.scrollTop(Math.abs(fgt.top - ios.top));
					} else if (ios.top + $item.outerHeight() > $container.height()) {
						$container.scrollTop(Math.abs(fgt.top - $item.outerHeight() - (ios.top - $container.height())));
					}
					*/
					
				} // 选择订单列表中的商品(修改数量)
				else if (focusType === focusTypes.AMOUNT || focusType === focusTypes.ADD) {
					
					focusType = focusTypes.AMOUNT;
					
					var $items = $(sel.listGoods());
					if ($items.length === 0) {
						return false;
					}
					var curIndex = $items.filter(".active").index(sel.listGoods());
					var nextIndex = 0;
					$items.removeClass("active");
					if (type === 'up') {
						nextIndex = ((curIndex === -1 || curIndex === 0)  ? $items.length: curIndex) - 1;
					} else {
						nextIndex = (curIndex === $items.length - 1 ? -1 : curIndex) + 1;
					}
					
					var $item = $items.eq(nextIndex);
					$item.addClass("active");
					
					// 数量文本框
					$(sel.amount()).eq(nextIndex).select().click();
					
					// 使显示在可见区域
					var itemOffset = $item.offset();
					var $title = $(sel.listTitle);
					var titleHeight = $title.outerHeight();
					var listOffset = $title.offset();
					if (itemOffset.top < (listOffset.top + titleHeight)) {
						$(window).scrollTop($(window).scrollTop() - (listOffset.top - itemOffset.top) - titleHeight);
					}
				}
				return false;
			}
			
		})($);
		
		
	})
	
});
